package com.smileus.common;

import java.io.Serializable;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smileus.util.JSONUtil;

/**
 * 参数对象，封装参数值，及其类型
 * 
 * @author heng.dong
 * 
 */
@SuppressWarnings("unchecked")
public class Param implements Serializable {
	private Object value;
	// private Class type;//定义Class，会与服务端产生耦合，因为目标服务参数，可能客户端没有该Class
	private String type;// 完整路径
	private static final long serialVersionUID = 1L;

	public Object getValue() {
		return value;
	}

	/**
	 * 确信Object不为null的使用，且该对象在目标服务器也存在
	 * @param value
	 */
	public Param(Object value) {
		super();
		if (value == null) {
			throw new RuntimeException("实例化Param失败，传入的value对象为null!");
		}
		this.value = value;
		this.type = value.getClass().getName();

	}

	public void setValue(Object value) {
		this.value = value;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public static Param toParam(Object source) {
		Param param = new Param();
		Class clazz = null;
		Object curtValue = null;
		JSONObject json = null;
		// JSONObject.parseObject要加强下才行-_-
		if (source != null && source.getClass() == JSONObject.class) {
			json = (JSONObject) source;
		} else {
			String jsonString = JSONObject.toJSONString(source);
			json = JSONObject.parseObject(jsonString);
		}
		try {
			clazz = Class.forName(json.getString("type"));
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
		curtValue = JSONUtil.toTarget(json.getString("value"), clazz);
		param.setValue(curtValue);
		return param;
	}

	public static String toJSONArray(Param... params) {
		if (params != null && params.length != 0) {
			return JSONArray.toJSONString(params);
		}
		return "[]";
	}

	public Param() {
		super();
	}

	public Param(Object value, Class type) {
		super();
		this.value = value;
		this.type = type.getName();
	}

	public Param(Object value, String type) {
		super();
		this.value = value;
		this.type = type;
	}
}
